// pages/order/order-page.js
const util = require('../../util/util.js');
const app = getApp()
import { obj_address, obj_coupon} from '../../util/model.js';

import { RequestManager } from '../../util/requestManager.js'
let requestManager = new RequestManager()

import { configLink } from '../../util/config.js'

var QQMapWX = require('../../util/libs/qqmap-wx-jssdk.js');
var qqmapsdk;


//  店铺的经纬度坐标
const fromValue = '31.29425,121.45791'
const appKey = '7K7BZ-EBOWW-NRVRY-R7NER-HXNR6-ZPFT4'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    conentMarginTop: 0,
    isPhoneX: false,
    is_delivery: true,
    switch_animation:{},

    minDay:'2019-11-27',

    reserveDay:'2019-11-26',
    weekDay:1,
    weekDayString:"周一",
    reserveTimeString: '11:00-11:59 AM',
    reserveTimes: ['11:00-11:59 AM', '12:00-14:59 PM', '15:00-17:59 PM','18:00-19:59 PM'],
    reserveTimeIndex: 0,

    cartGoodsItems:[],
    //  收货地址
    addressItem: null,
    //  可配送
    isCanSend:true,

    //  门店地址
    storeInfo: null,
    //  优惠券
    coupontItem: null,
    //  优惠金额
    discount:'0.00',
    //  积分
    point:0,
    //  总金额
    totalAmount:'0.00',
    //  总价格
    orderAmount:'0.00',
    //  是否同意协议
    isAgreement:false,
    //  备注信息
    remark:'',

    // 订单的支付信息（缓存）
    payInfoCache:null,
    isContinuePayment:false,
    //  订单id
    orderId:null,

    //  用户是否授权登录
    isLogin:false,

    //  是否有限购的商品导致无法下单
    isCanBuy:true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let cartGoodsItems = JSON.parse(options.items);
    var totalAmount = 0.00;
    cartGoodsItems.forEach((tmpItem)=>{
      totalAmount += (tmpItem.amount);
    });

    let animation = util.moveXAnimation(0);
    this.setData({
      switch_animation: animation,
      cartGoodsItems: cartGoodsItems,
      totalAmount:totalAmount.toFixed(2),
      orderAmount: totalAmount.toFixed(2),
      isPhoneX: app.globalData.isIphoneX,
      conentMarginTop: app.globalData.navHeight,
      isLogin: app.globalData.userInfo === null ? false : true,
    });

    this.private_getCurrentDateInfo()
  },

  onShow:function(){
    this.setData({
      isContinuePayment: false
    })
    this.private_getOrderAmountInfo()
  },

  onUnload:function(){
    if (this.data.isContinuePayment && this.data.orderId != null){
      //  对于没有支付的订单，当退出当前page时，需要把订单取消掉
      this.private_cancelPay()
    }
  },

  //  切换送货方式
  action_switch: function (event) {
    var switchValue = event.target.dataset.id
    let tmpValue = switchValue == "1" ? false : true

    if(this.data.is_delivery == tmpValue){
      return
    }

    if (this.data.isContinuePayment && this.data.orderId != null) {
      //  对于没有支付的订单，送货方式修改则需要取消掉原来掉订单信息
      this.private_cancelPay()
    }

    let animation = util.moveXAnimation(switchValue == "1" ? 100 : 0);
    var tmpCanSend = true;
    if (this.data.addressItem && switchValue == "0"){
      tmpCanSend = this.data.addressItem.distanceCost == -1 ? false : true
    }
    this.setData({
      is_delivery: tmpValue,
      switch_animation:animation,
      isCanSend: tmpCanSend
    });

    this.private_getOrderAmountInfo()
  },
  //  选择地址
  action_address:function(event){

    var that = this
    util.getUserAddressInfo(addressInfo=>{
      console.log(addressInfo)
      //  判断地址是否为浦东新区，如果是浦东新区则需要额外再添加6元快递费
      var isExtra = addressInfo.countyName.indexOf("浦东") != -1 ? true : false

      var tmpAddressItem = {
        name: addressInfo.userName,
        phone: addressInfo.telNumber,
        address: addressInfo.provinceName + addressInfo.cityName + addressInfo.countyName + addressInfo.detailInfo,
        provinceName: addressInfo.provinceName,
        cityName: addressInfo.cityName,
        countyName: addressInfo.countyName,
        detailInfo: addressInfo.detailInfo,
        distanceCost: -1,
        isExtra: isExtra
      }
      that.setData({
        addressItem: tmpAddressItem,
        isCanSend: true
      })
      that.private_getAddressDistance()
    });
    return;
  },
  //  同意协议
  action_agreement:function(event){
    this.setData({
      isAgreement: !this.data.isAgreement
    })
  },
  //  提交订单
  action_submit: function (event) {

    if(!this.data.isCanBuy){
      wx.showModal({
        title: '提示',
        content: '订单中存在限时购商品，请您更换日期',
        showCancel: false,//是否显示取消按钮
        confirmText: "更改",//默认是“确定”
      })
      return
    }

    if (this.data.coupontItem != null && this.data.coupontItem.couponType == 2){
      var that = this;
      if (this.data.discount > this.data.orderAmount){
        wx.showModal({
          title: '提示',
          content: '此卡仅限于一次性购物抵扣，并不设余额和找零。请尽量根据卡上面值购买相应产品。\n 确认要使用该抵用卷吗？',
          showCancel: true,//是否显示取消按钮
          cancelText: "再看看",//默认是“取消”
          confirmText: "确认使用",//默认是“确定”
          success(res){
            if(res.confirm){
              that.private_submitOrder()
            }
          }
        })
        return;
      }
    }
    this.private_submitOrder()
  },
  //  继续支付
  action_continuePayment:function(event){
    this.private_gotoPay()
  },
  action_agreementDetail:function(event){
    var url = configLink.agreement
    wx.downloadFile({
      url:url,
      success:function(result){
        let tmpFilePath = result.tempFilePath;
        wx.openDocument({
          filePath: tmpFilePath,
          fileType:'pdf',
          complete:function(result){
            // console.log('',result);
          }})
      },
      fail:function(err){
        // console.log(err)
      }
    })
  },
  //  获取日期
  bindDateChange: function (event) {

    let tmpDayString = event.detail.value;
    var date = new Date(tmpDayString);//就是这么简单
    let weekIndex = date.getDay()
    
    let weekDayString = util.getWeekDay(date);

    this.setData({
      reserveDay: event.detail.value,
      weekDay: weekIndex,
      weekDayString: weekDayString
    })
    this.private_handleFixBuy(weekIndex);
  },
  //  获取时间
  bindTimeChange: function (event) {
    let timeIndex = event.detail.value
    this.setData({
      reserveTimeIndex: timeIndex,
      reserveTimeString: this.data.reserveTimes[timeIndex]
    })
  },
  //  文本编辑
  bindEndEdit:function(event){
    this.setData({
      remark:event.detail.value
    })
  },
  //  获取当前时间
  private_getCurrentDateInfo(){
    var currentDate = new Date();
    currentDate.setTime(currentDate.getTime() + 24*3600*1000 * 3)
    //  设置需要提前三天下单...

    let weekIndex = currentDate.getDay()
    let weekDayString = util.getWeekDay(currentDate);

    this.setData({
      minDay: currentDate.format("yyyy-MM-dd"),
      reserveDay: currentDate.format("yyyy-MM-dd"),
      weekDay:weekIndex,
      weekDayString: weekDayString
    })

    this.private_handleFixBuy(weekIndex);
  },
  //  获取选择的地址距离门店的距离
  private_getAddressDistance(){

    var that = this;
    let tmpAddress = this.data.addressItem

    qqmapsdk = new QQMapWX({
      key: appKey
    })

    qqmapsdk.geocoder({
      address: tmpAddress.address,
      success: function (res) {
        let location = res.result.location
        qqmapsdk.calculateDistance({
          mode: 'walking',
          from: fromValue,
          to: location.lat + ',' + location.lng,
          success: function (res) {
            let distance = res.result.elements[0].distance
            tmpAddress.distance = (distance/1000).toFixed(2) + "km"
            //  配送费
            let distanceCost = util.distributionCost(distance, that.data.totalAmount)
            //  如果当前地址为浦东新区的话，则需要额外再+6元的过江费用
            var distanceCostText = "超出配送范围，请联系客服"
            if (distanceCost != -1){
              distanceCost += (tmpAddress.isExtra ? 6 : 0)
              distanceCostText = "此订单快递费用" + distanceCost + "元"
            }

            tmpAddress.distanceCost = distanceCost
            tmpAddress.distanceCostText = distanceCostText
            that.setData({
              addressItem: tmpAddress,
              isCanSend: tmpAddress.distanceCost == -1 ? false : true
            })
            that.private_getOrderAmountInfo()
          }
        })
      }
    })
  },
  //  计算订单的金额信息
  private_getOrderAmountInfo(){
    var discount = 0.0;
    if (this.data.coupontItem) {
      if (this.data.coupontItem.couponType == 2) {
        discount = this.data.coupontItem.money;
      }
      else {
        discount = this.data.totalAmount * (1 - this.data.coupontItem.discount/100);
      }
    }

    var tmpOrderAmount = this.data.totalAmount - discount
    if (tmpOrderAmount < 0) {
      tmpOrderAmount = 0;
    }

    //  送货上门，并且收获地址在配送范围之内
    if (this.data.is_delivery && this.data.addressItem != null && this.data.addressItem.distanceCost != -1) {
      tmpOrderAmount += this.data.addressItem.distanceCost
    }

    this.setData({
      discount: discount.toFixed(2),
      orderAmount: tmpOrderAmount.toFixed(2)
    });
  },
  //  点击确认订单按钮操作
  private_submitOrder(){

    if (!this.data.isAgreement) {
      wx.showToast({
        title: "请先阅读并同意用户订购协议",
        icon: 'none'
      });
      return;
    }

    if (this.data.is_delivery) {
      //  送货上门
      if (this.data.addressItem == null) {
        wx.showToast({
          title: "请先选择收货地址",
          icon: 'none'
        });
        return;
      }
      //  如果是需要快递送货的订单，需要先把收货地址信息提交给后台。然后获取到地址id，再把订单信息提交给后台
      wx.showLoading({
        title: '提交中...',
      })
      var that = this
      requestManager.addAddressItemToWeb(app.globalData.openid, this.data.addressItem.name, this.data.addressItem.provinceName, this.data.addressItem.cityName, this.data.addressItem.countyName + this.data.addressItem.detailInfo, this.data.addressItem.phone, result => {
        that.private_createOrder(result['id']);
      });
    }
    else {
      wx.showLoading({
        title: '提交中...',
      })
      this.private_createOrder("-1");
    }
  },
  //  发送提交订单接口操作
  private_createOrder(addressId){
    var goodlist = []
    this.data.cartGoodsItems.forEach((tmpItem)=>{
      goodlist.push({ "goodid": tmpItem.goodsItem.id, "sizeid": tmpItem.sizeItem.id, "tasteid": tmpItem.optionItem.id, "number": tmpItem.count})
  })

    var that = this;

    var tmpTimesStrings = this.data.reserveTimeString.split("-")

    var bookdate = this.data.reserveDay + " " + tmpTimesStrings[0] +":00"
   tmpTimesStrings = tmpTimesStrings[1].split(" ")
    var bookenddate = this.data.reserveDay + " " + tmpTimesStrings[0] + ":00"
    var couponId = this.data.coupontItem != null ? this.data.coupontItem.id : '-1'
    var deliveryfee = this.data.addressItem != null ? this.data.addressItem.distanceCost : "0"

    if (!this.data.is_delivery){
      deliveryfee = '0';
    }
    
    requestManager.addOrderItemToWeb(app.globalData.openid, deliveryfee, couponId, addressId, goodlist, bookdate, bookenddate,this.data.remark,result=>{

      that.private_removeItemFromCart();

      //  如果支付金额为0的情况下，直接跳转到我的订单列表界面
      // console.log("....",that.data.orderAmount)
      if (that.data.orderAmount == "0.00"){
        wx.hideLoading();
        wx.navigateTo({
          url: '/pages/user/user-order-page?source=order',
        })
        return;
      }

      var orderid = result.id
      that.private_getOrderPayInfo(orderid);
    })
  },
  //  获取订单支付信息
  private_getOrderPayInfo(orderid){
    requestManager.payOrderItem(app.globalData.openid,orderid,resulut=>{
      this.setData({
        payInfoCache: resulut,
        orderId:orderid
      })
      this.private_gotoPay();
    })
  },
  //  订单生成之后需要把对应的商品从购物车中移除
  private_removeItemFromCart(){

    var goodids = []
    this.data.cartGoodsItems.forEach((tmpItem) => {
      goodids.push(tmpItem.id)
    })

    requestManager.removeGoodsItemFromCart(app.globalData.openid, goodids.join(','), success => {
    })
  },
  //  取消订单
  private_cancelPay(){

    this.setData({
      isContinuePayment: false,
    });

    if(this.data.orderId != null){
      requestManager.cancelOrder(app.globalData.openid, this.data.orderId, result => {
        // console.log("取消订单成功")
      })
    }
  },
  //  调用微信支付
  private_gotoPay(){

    wx.hideLoading();

    let timeStamp = this.data.payInfoCache['timestamp'];
    let nonceStr = this.data.payInfoCache['nonce_str'];
    let _package = this.data.payInfoCache['package'];
    let paySign = this.data.payInfoCache['sign'];

    var that = this
    wx.requestPayment({
      timeStamp: timeStamp,
      nonceStr: nonceStr,
      package: _package,
      signType: 'MD5',
      paySign: paySign,
      success: function (result) {
        wx.navigateTo({
          url: '/pages/user/user-order-page?source=order',
        })
      },
      fail: function (error) {
        wx.showToast({
          title: '支付失败',
        })
        that.setData({
          isContinuePayment:true
        })
      }
    })
  },
  //  授权获取用户信息
  private_getUserInfo: function (result) {

    let userInfo = result.detail.userInfo;
    if (userInfo != null) {
      //  授权获取用户信息
      app.saveWXUserInfo(userInfo)

      let nickName = userInfo.nickName
      let head = userInfo.avatarUrl
      var that = this;
      requestManager.userRegister(app.globalData.openid, nickName, head, (reslut) => {
      });
      this.setData({
        isLogin: true
      })
    }
  },
  //  处理当前订单中是否有限购日期的商品
  private_handleFixBuy(weekDay){
    var tmpCanBuy = true
    this.data.cartGoodsItems.forEach((tmpGoodsItem) => {
      if(tmpGoodsItem.goodsItem.fixdays != null) {

        var itemCanBuy = false

        tmpGoodsItem.goodsItem.fixdays.forEach((fixday) => {
          if (weekDay == 0) {
            itemCanBuy = itemCanBuy || (parseInt(fixday) === 7)
          }
          else {
            itemCanBuy = itemCanBuy || (parseInt(fixday) === weekDay)
          }
        })
        tmpCanBuy = tmpCanBuy && itemCanBuy
      }
    })
    this.setData({
      isCanBuy: tmpCanBuy
    })
  }
})